/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.AgendaDAO;
import dao.UsuarioDAO;
import dao.HorarioDAO;
import dao.ServicosDAO;
import dao.impl.AgendaDAOImpl;
import dao.impl.UsuarioDAOImpl;
import dao.impl.HorarioDAOImpl;
import dao.impl.ServicosDAOImpl;
import java.net.URLDecoder;
import java.sql.Date;
import java.sql.Time;
import java.util.List;
import model.Usuario;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import model.Agenda;
import model.Horarios;
import model.Servicos;

/**
 *
 * @author MauroH
 */
public class AgendouServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        // Pega o parametro cmd da requisição, se for nulo atribui o valor 'listarAgendaDisponivel'
        String cmd = request.getParameter("cmd");
        String redirect = request.getParameter("redirect");
        if (cmd == null) {
            cmd = "principal";
        }
        if (redirect == null) {
            redirect = "";
        }

        // Cria objetos
        UsuarioDAO usuarioDAO;
        HorarioDAO horarioDAO;
        AgendaDAO agendaDAO;
        AgendaDAO agendaDAO2;
        ServicosDAO servicoDAO;

        // Instancia objetos
        Usuario usuario = new Usuario();
        Horarios horario = new Horarios();
        Servicos servico = new Servicos();

        // Verifica se o valor do cmd é referente ao usuario e seta os valores dos atributos
        if (cmd.equalsIgnoreCase("autenticarUsuario")
                || cmd.equalsIgnoreCase("logout")) {
            usuario.setUsername(request.getParameter("username"));
            usuario.setSenha(request.getParameter("senha"));
        } else if (cmd.equalsIgnoreCase("procurarUsuario")
                || cmd.equalsIgnoreCase("addUsuario")
                || cmd.equalsIgnoreCase("excUsuario")
                || cmd.equalsIgnoreCase("atuUsuario")
                || cmd.equalsIgnoreCase("atualizarUsuario")) {
            usuario.setCpf(request.getParameter("cpf"));
            usuario.setUsername(request.getParameter("username"));
            usuario.setSenha(request.getParameter("senha"));
            usuario.setNome(request.getParameter("nome"));
            try {
                String nascimento[] = request.getParameter("dt_nascimento").split("/");
                usuario.setDt_nascimento(Date.valueOf(nascimento[2] + "-" + nascimento[1] + "-" + nascimento[0]));
            } catch (Exception e) {
                String nascimento[] = null;
            }
            usuario.setSexo(request.getParameter("sexo"));
            usuario.setEmail(request.getParameter("email"));
            usuario.setTelefone(request.getParameter("telefone"));
        } // Verifica se o valor do cmd é referente aos horarios e seta os valores dos atributos
        else if (cmd.equalsIgnoreCase("todosHorarios")
                || cmd.equalsIgnoreCase("excHorarios")) {
            try {
                String dataHorario[] = request.getParameter("data").split("/");
                horario.setData(Date.valueOf(dataHorario[2] + "-" + dataHorario[1] + "-" + dataHorario[0]));
            } catch (Exception e) {
                String dataHorario[] = null;
            }
            System.out.println(request.getParameter("horario"));
            horario.setHorario(Time.valueOf(request.getParameter("horario")));

            horario.setDiaSemana(request.getParameter("diaSemana"));
        } // 
        else if (cmd.equalsIgnoreCase("addAgenda")) {
            horario.setData(Date.valueOf(request.getParameter("data")));
            horario.setHorario(Time.valueOf(request.getParameter("horario")));
        } // Verifica se o valor do cmd é referente aos horarios e seta os valores dos atributos

        try {
            horarioDAO = new HorarioDAOImpl();
            usuarioDAO = new UsuarioDAOImpl();
            agendaDAO = new AgendaDAOImpl();
            agendaDAO2 = new AgendaDAOImpl();
            servicoDAO = new ServicosDAOImpl();
            RequestDispatcher rd = null;

            if (cmd.equalsIgnoreCase("addAgenda")) {
                List listaServicos = servicoDAO.todosServicos();
                request.setAttribute("horario", horarioDAO.getHorario(horario));
                request.setAttribute("servicos", listaServicos);
                rd = request.getRequestDispatcher("/agendarHorario.jsp");
            }


            //******************************************************
//             OPERACOES NA TABELA HORARIOS
            if (cmd.equalsIgnoreCase("addHorarios")) {
                String data = "";
                //faz o split da data com o delimitar /
                if (request.getParameter("data") == null || request.getParameter("data").trim().equals("")) {
                    request.setAttribute("e_data", "erro");

                }
                if (request.getParameter("diaSemana") == null || request.getParameter("diaSemana").trim().equals("")) {
                    request.setAttribute("e_diaSemana", "erro");
                }
                if (request.getParameter("horario") == null || request.getParameter("horario").trim().equals("")) {
                    request.setAttribute("e_horario", "erro");

                }
                if (request.getParameter("data") != null || !request.getParameter("data").trim().equals("")) {
                    String formatoData = "^([0-9]{2}\\/[0-9]{2}\\/[0-9]{4})$";
                    if (request.getParameter("data").length() != 10 || !request.getParameter("data").matches(formatoData)) {
                        request.setAttribute("e_data", "erro");
                        data = null;
                    }

                }
                if (request.getParameter("data") == null || request.getParameter("data").trim().equals("") || data == null
                        || request.getParameter("diaSemana") == null || request.getParameter("diaSemana").trim().equals("")
                        || request.getParameter("horario") == null || request.getParameter("horario").trim().equals("")) {
                    request.setAttribute("msg", "Favor preencher o(s) campo(s) destacado(s) corretamente!");
                    request.setAttribute("data", request.getParameter("data"));
                    request.setAttribute("diaSemana", request.getParameter("diaSemana"));
                    request.setAttribute("horario", request.getParameter("horario"));
                    rd = request.getRequestDispatcher("cadHorarios.jsp");
                } else {
                    String dt[] = request.getParameter("data").split("/");

                    //converte o formato passado como parÃ¢metro para o formato xxxx-xx-xx                
                    horario.setData(Date.valueOf(dt[2] + "-" + dt[1] + "-" + dt[0]));

                    //atribui valor aos atributos
                    horario.setHorario(Time.valueOf(request.getParameter("horario")));
                    horario.setDiaSemana(request.getParameter("diaSemana"));
                    horarioDAO.salvar(horario);
                    rd = request.getRequestDispatcher("agenda?cmd=listarAgendaDisponivel");

                }
            }

            if (cmd.equalsIgnoreCase("listarAgendaDisponivel")) {

                List listaAgendaDisponivel = agendaDAO.getAgendas(true);
                request.setAttribute("listaAgendaDisponivel", listaAgendaDisponivel);

                try {
                    HttpSession sessao = request.getSession(false);
                    usuario = (Usuario) sessao.getAttribute("usuario");

                    if (usuario.getIs_admin() == true) {
                        List listaAgendaIndisponivel = agendaDAO2.getAgendas(false);
                        request.setAttribute("listaAgendaIndisponivel", listaAgendaIndisponivel);
                    }
                } catch (Exception e) {
                }

                rd = request.getRequestDispatcher("/agenda.jsp?cmd=listarAgendaDisponivel");
            }

            // OPERACOES NA TABELA AGENDA
            if (cmd.equalsIgnoreCase("agendarHorario")) {
                usuario.setCpf(request.getParameter("cpf"));
                usuario = usuarioDAO.procurarUsuario(usuario.getCpf());

                String dt[] = request.getParameter("data").split("/");

                horario.setData(Date.valueOf(dt[2] + "-" + dt[1] + "-" + dt[0]));
                horario.setHorario(Time.valueOf(request.getParameter("horario") + ":00"));
                horario = horarioDAO.getHorario(horario);

                servico.setNomeServico(request.getParameter("servico"));
                servico = servicoDAO.getServico(servico);

                agendaDAO.salvar(usuario, servico, horario);
                rd = request.getRequestDispatcher("agenda?cmd=listarAgendaDisponivel");
            } else if (cmd.equalsIgnoreCase("visualizarAgenda")) {
                Agenda agenda = new Agenda();
                agenda = agendaDAO.getAgenda(Integer.parseInt(request.getParameter("idhorario")));
                request.setAttribute("user", usuarioDAO.procurarUsuario(agenda.getUsuario().getCpf()));
                request.setAttribute("horario", horarioDAO.getHorario(Integer.parseInt(request.getParameter("idhorario"))));
                request.setAttribute("servico", servicoDAO.getServico(agenda.getServico().getIdservicos()));

                rd = request.getRequestDispatcher("/visualizarAgenda.jsp");
            } else if (cmd.equalsIgnoreCase("desmarcarAgenda")) {
                Agenda agenda = new Agenda();
                agenda = agendaDAO.getAgenda(Integer.parseInt(request.getParameter("idhorario")));
                request.setAttribute("user", usuarioDAO.procurarUsuario(agenda.getUsuario().getCpf()));
                request.setAttribute("horario", horarioDAO.getHorario(Integer.parseInt(request.getParameter("idhorario"))));
                request.setAttribute("servico", servicoDAO.getServico(agenda.getServico().getIdservicos()));

                rd = request.getRequestDispatcher("/excluirAgenda.jsp");
            } else if (cmd.equalsIgnoreCase("excluirAgenda")) {
                agendaDAO.excluir(Integer.parseInt(request.getParameter("idhorario")));
                rd = request.getRequestDispatcher("agenda?cmd=listarAgendaDisponivel");
            }
            // OPERACOES NA TABELA CLIENTE
            if (cmd.equalsIgnoreCase("autenticarUsuario")) {
                try {
                    HttpSession sessao = request.getSession(true);
                    sessao.removeAttribute("usuario");
                    usuario = usuarioDAO.procurarUsuario(usuario.getUsername(), usuario.getSenha());
                    sessao.setAttribute("usuario", usuario);
                    if (usuario.getCpf() != null && !usuario.getCpf().trim().equals("")) {
                        if (redirect.equalsIgnoreCase("")) {
                            rd = request.getRequestDispatcher("agenda?cmd=listarAgendaDisponivel"); //verificar nome das paginas

                        } else {
                            rd = request.getRequestDispatcher(URLDecoder.decode(redirect.toString())); //verificar nome das paginas
                        }

                    } else {
                        request.setAttribute("msg", "Usuário ou senha inválido(s)");
                        rd = request.getRequestDispatcher("/login.jsp"); //verificar nome das paginas
                    }
                } catch (Exception e) {
                    request.setAttribute("msg", "Usuário ou senha inválido(s)");
                    rd = request.getRequestDispatcher("/login.jsp"); //verificar nome das paginas
                }
            } else if (cmd.equalsIgnoreCase("addUsuario")) {

                HttpSession sessao = request.getSession(true);
                sessao.removeAttribute("usuario");
                /**
                 * Variáveis de validação
                 */
                String telefone = "";
                String data = "";
                String cpf = "";

                if (request.getParameter("username") == null || request.getParameter("username").trim().equals("")) {
                    request.setAttribute("e_username", "erro");

                }
                if (request.getParameter("senha") == null || request.getParameter("senha").trim().equals("")) {
                    request.setAttribute("e_senha", "erro");

                }
                if (request.getParameter("nome") == null || request.getParameter("nome").trim().equals("")) {
                    request.setAttribute("e_nome", "erro");

                }
                if (request.getParameter("cpf") == null || request.getParameter("cpf").trim().equals("")) {
                    request.setAttribute("e_cpf", "erro");

                }
                if (request.getParameter("dt_nascimento") == null || request.getParameter("dt_nascimento").trim().equals("")) {
                    request.setAttribute("e_dt_nascimento", "erro");

                }
                if (request.getParameter("email") == null || request.getParameter("email").trim().equals("")) {
                    request.setAttribute("e_email", "erro");

                }
                if (request.getParameter("telefone") == null || request.getParameter("telefone").trim().equals("")) {
                    request.setAttribute("e_telefone", "erro");

                }
                if (request.getParameter("sexo") == null || request.getParameter("sexo").trim().equals("")) {
                    request.setAttribute("e_sexo", "erro");

                }
                if (request.getParameter("cpf") != null || !request.getParameter("cpf").trim().equals("")) {
                    String formatoCpf = "^[0-9]{3}.?[0-9]{3}.?[0-9]{3}-?[0-9]{2}";
                    if (request.getParameter("cpf").length() != 14 || !request.getParameter("cpf").matches(formatoCpf)) {
                        request.setAttribute("e_cpf", "erro");
                        cpf = null;
                    }
                }
                if (request.getParameter("telefone") != null || !request.getParameter("telefone").trim().equals("")) {
                    String formatoTelefone = "^\\([0-9]{2}\\)[0-9]{4}-[0-9]{4}";
                    if (request.getParameter("telefone").length() < 13 || !request.getParameter("telefone").matches(formatoTelefone)) {
                        request.setAttribute("e_telefone", "erro");
                        telefone = null;
                    }
                }
                if (request.getParameter("dt_nascimento") != null || !request.getParameter("dt_nascimento").trim().equals("")) {
                    String formatoData = "^([0-9]{2}\\/[0-9]{2}\\/[0-9]{4})$";
                    if (request.getParameter("dt_nascimento").length() != 10 || !request.getParameter("dt_nascimento").matches(formatoData)) {
                        request.setAttribute("e_dt_nascimento", "erro");
                        data = null;
                    }
                }

                if (request.getParameter("username") == null || request.getParameter("username").trim().equals("")
                        || request.getParameter("senha") == null || request.getParameter("senha").trim().equals("")
                        || request.getParameter("nome") == null || request.getParameter("nome").trim().equals("")
                        || request.getParameter("cpf") == null || request.getParameter("cpf").trim().equals("") || cpf == null
                        || request.getParameter("dt_nascimento") == null || request.getParameter("dt_nascimento").trim().equals("") || data == null
                        || request.getParameter("email") == null || request.getParameter("email").trim().equals("")
                        || request.getParameter("telefone") == null || request.getParameter("telefone").trim().equals("") || telefone == null
                        || request.getParameter("sexo") == null || request.getParameter("sexo").trim().equals("")) {
                    request.setAttribute("msg", "Favor preencher o(s) campo(s) destacado(s) corretamente!");
                    request.setAttribute("username", request.getParameter("username"));
                    request.setAttribute("senha", request.getParameter("senha"));
                    request.setAttribute("nome", request.getParameter("nome"));
                    request.setAttribute("cpf", request.getParameter("cpf"));
                    request.setAttribute("dt_nascimento", request.getParameter("dt_nascimento"));
                    request.setAttribute("email", request.getParameter("email"));
                    request.setAttribute("telefone", request.getParameter("telefone"));
                    request.setAttribute("sexo", request.getParameter("sexo"));

                    rd = request.getRequestDispatcher("cadastro.jsp");
                } else {
                    usuarioDAO.salvar(usuario);
                    sessao.setAttribute("usuario", usuario);
                    rd = request.getRequestDispatcher("login.jsp");
                }
                rd = request.getRequestDispatcher("/cadastro.jsp");
            } else if (cmd.equalsIgnoreCase("logout")) {
                HttpSession sessao = request.getSession(true);
                sessao.removeAttribute("usuario");
                rd = request.getRequestDispatcher("agenda?cmd=listarAgendaDisponivel"); //verificar nome das paginas
            } else if (cmd.equalsIgnoreCase("principal")) {
                rd = request.getRequestDispatcher("/agenda?cmd=listarAgendaDisponivel"); //verificar nome das paginas
            }
            rd.forward(request, response);
        } catch (Exception e) {
            //e.printStackTrace( );
            throw new ServletException(e);
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet AgendouServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet AgendouServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
